<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
            <el-form-item label="省" prop="provinceId">
                <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                    <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="市" prop="cityId">
                <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable
                    :disabled="cityDisabled">
                    <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="区/县" prop="areaId">
                <el-select v-model="queryParams.areaId" placeholder="请选择区/县" @change="chooseArea" clearable
                    :disabled="areaDisabled">
                    <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="上传人" prop="uploadUserName">
                <el-input v-model="queryParams.uploadUserName" placeholder="请输入上传人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="上传日期">
                <el-date-picker v-model="uploadTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="图件名称" prop="mapName">
                <el-input v-model="queryParams.mapName" placeholder="请输入图件名称" clearable />
            </el-form-item>
            <el-form-item label="一级图件分类" prop="mapLevel1Category">
                <el-select v-model="queryParams.mapLevel1Category" placeholder="请选择一级图件分类" clearable
                    @change="changeCategory">
                    <el-option v-for="item in chartClassifyOption" :key="item.dictId" :label="item.dictName"
                        :value="item.dictId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="二级图件分类" prop="mapLevel2Category">
                <el-select v-model="queryParams.mapLevel2Category" placeholder="请选择二级分类" clearable>
                    <el-option v-for="item in chartClassifyOption1" :key="item.dictItemId" :label="item.dictItemName"
                        :value="item.dictItemId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label=" ">
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">上传</el-button>
                <el-button type="primary" plain @click="handleDowon">下载</el-button>
                <el-button type="primary" plain @click="handleDelete">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="dmId"
            ref="tableRef" tooltip-effect="light">
            <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
            <el-table-column label="图件名称" align="center" prop="mapName">
                <template #default="scope">
                    <el-button type="text" @click="handleView(scope.row)">{{ scope.row.mapName }}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="图件分类" align="center" prop="mapClassify" show-overflow-tooltip>
                <template #default="scope">
                    <span>{{ scope.row.mapLevel1Category }}</span><br>
                    <span>{{ scope.row.mapLevel2Category }}</span>
                </template>
            </el-table-column>
            <el-table-column label="图件描述" align="center" prop="mapDesc">
                <template #default="{ row }">
                    <el-popover placement="right" :width="400" trigger="click" v-if="row.mapDesc">
                        <template #reference>
                            <el-button type="text">查看</el-button>
                        </template>
                        <el-card shadow="never">
                            <template #header>
                                <div class="card-header">
                                    <span>图件描述</span>
                                </div>
                            </template>
                            <div v-html="mapDescHtml(row.mapDesc)"></div>
                        </el-card>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="地区" align="center" prop="district" />
            <el-table-column label="上传人" align="center" prop="uploadUserName" />
            <el-table-column label="上传日期" align="center" prop="uploadTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <!-- 图件上传 -->
        <el-dialog :title="title" v-model="open" width="800px" append-to-body>
            <el-form ref="uploadRef" :model="form" :rules="rules" label-width="120px">
                <el-row class="mt15">
                    <el-col :span="24">
                        <el-form-item label="图件名称" prop="mapName">
                            <el-input style="width: 100%;" v-model="form.mapName" placeholder="请输入图件名称"
                                :disabled="isView" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="图件分类" prop="mapClassify">
                            <el-form-item label-width="0px" prop="mapLevel1Category">
                                <el-select v-model="form.mapLevel1Category" placeholder="请选择一级图件分类" @change="changeLevel1"
                                    clearable :disabled="isView">
                                    <el-option v-for="item in chartClassifyOption" :key="item.dictId" :label="item.dictName"
                                        :value="item.dictId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label-width="0px" prop="mapLevel2Category" style="margin-left: 60px;">
                                <el-select v-model="form.mapLevel2Category" placeholder="请选择二级图件分类" @change="changeLevel2"
                                    clearable :disabled="isView">
                                    <el-option v-for="item in chartClassifyOption2" :key="item.dictItemId"
                                        :label="item.dictItemName" :value="item.dictItemId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-if="isView">
                    <el-col :span="8">
                        <el-form-item label="省" prop="provinceId">
                            <el-input v-model="form.province" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市" prop="cityId">
                            <el-input v-model="form.city" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区/县" prop="areaId">
                            <el-input v-model="form.area" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-if="!isView">
                    <el-col :span="8">
                        <el-form-item label="省" prop="provinceId">
                            <el-select v-model="form.provinceId" placeholder="请输入省" @change="chooseFormProvince"
                                style="width: 100%;">
                                <el-option v-for="item in provinceFormData" :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市" prop="cityId">
                            <el-select v-model="form.cityId" placeholder="请输入市" @change="chooseFormCity"
                                style="width: 100%;" :disabled="cityFormDisabled">
                                <el-option v-for="item in cityFormData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区/县" prop="areaId">
                            <el-select v-model="form.areaId" placeholder="请输入区/县" @change="chooseFormArea"
                                style="width: 100%;" :disabled="areaFormDisabled">
                                <el-option v-for="item in areaFormData" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="图片" prop="attachmentId">
                            <image-upload ref="imgUpload" :fileSize="100" :limit="1" v-model="form.attachList"
                                :disabled="isView" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="图件描述" prop="mapDesc">
                            <el-input v-model="form.mapDesc" type="textarea" maxlength="1000" show-word-limit
                                :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入图件描述" :disabled="isView" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm" v-if="!isView">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="ChartManger">
import { queryMaps, saveMap, getDictByDictDirId, getDictItemsByDictId, getById, downLoadFile, deleteByIds } from "@/api/resultManage/chartManger";
import { getProvince, getChildArea } from "@/api/system/division";
import { reactive } from "vue";
import { saveAs } from 'file-saver'

const { proxy } = getCurrentInstance();


const dataList = ref([]);
const btnType = ref('add')
const open = ref(false);  //其他图件弹窗
const title = ref("");//弹窗标题
const isView = ref(false);// 是否是查看
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const idFiles = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const uploadDisabled = ref(false);

const uploadTime = ref("");//提交时间
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县

const provinceFormData = ref([]);//表单省 
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县
const taskList = ref([])

const chartClassifyOption = ref([]);
const chartClassifyOption1 = ref([]);
const chartClassifyOption2 = ref([]);
const validatorCity = (rule, value, callback) => {
    if (!value) {
        if (!form.value.province) {
            callback(new Error('请选择市'));
        } else if (form.value.province != '全国') {
            callback(new Error('请选择市'));
        } else {
            callback();
        }
    } else {
        callback();
    }
}
const validatorArea = (rule, value, callback) => {
    if (!value) {
        if (form.value.province == '全国') {
            callback();
        } else if ((form.value.city && form.value.city != '全部') || !form.value.city) {
            callback(new Error('请选择区/县'));
        } else {
            callback();
        }
    } else {
        callback();
    }
}
const data1 = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        taskName: null,
        province: null,
        provinceId: null,
        city: null,
        cityId: null,
        area: null,
        areaId: null,
        uploadUserName: null,
        uploadTime: null,
        startTime: null,
        endTime: null,
    },
});
const data2 = reactive({
    form: {},
    rules: {
        mapClassify: [{ required: true, trigger: "blur", validator: validatorMapClassify }],
        mapName: [{ required: true, message: "图件名称不能为空", trigger: "blur" }],
        mapDesc: [{ required: true, message: "图件描述不能为空", trigger: "blur" }],
        provinceId: [{ required: true, message: '请选择省', trigger: 'change' }],
        cityId: [{ trigger: 'change', validator: validatorCity }],
        areaId: [{ trigger: 'change', validator: validatorArea }],
        attachmentId: [{ required: true, message: "图件不能为空", trigger: "blur", validator: validatorImg }],
    }
});

const { queryParams } = toRefs(data1);
const { form, rules } = toRefs(data2);
const mapDescHtml = (mapDesc) => {
    return mapDesc ? mapDesc.split('').map(item => item == '\n' ? '<br>' : item).join('') : mapDesc
}
function imgSuccess(response, file, fileList) {
    uploadDisabled.value = true;
}

//自定义图片上传验证
function validatorImg(rule, value, callback) {
    if (proxy.$refs['imgUpload'].fileList.length > 0) {
        callback();
    } else {
        callback(new Error('图件不能为空'));
    }
}

//图片分类验证
function validatorMapClassify(rule, value, callback) {
    if (form.value.mapLevel1Category == '' || form.value.mapLevel1Category == undefined) {
        callback(new Error('图件分类不能为空'));
    } else if ((form.value.mapLevel1Category != '' || form.value.mapLevel1Category != undefined) && (form.value.mapLevel2Category == '' || form.value.mapLevel2Category == undefined)) {
        callback(new Error('二级图件分类不能为空'));
    } else if ((form.value.mapLevel1Category != '' || form.value.mapLevel1Category != undefined) && (form.value.mapLevel2Category != '' || form.value.mapLevel2Category != undefined)) {
        callback();
    }
}

function changeLevel1(value) {
    form.value.mapLevel2Category = '';
    if (value) {
        getChartClassifyList2(value);
    } else {
        chartClassifyOption2.value = [];
    }
    proxy.$refs['uploadRef'].validateField('mapClassify')
}

function changeLevel2() {
    proxy.$refs['uploadRef'].validateField('mapClassify')
}

function changeCategory(value) {
    queryParams.value.mapLevel2Category = '';
    if (value) {
        getChartClassifyList2(value);
    } else {
        chartClassifyOption1.value = [];
    }
}

/** 查询列表 */
function getList() {
    loading.value = true;
    queryMaps(queryParams.value).then(response => {
        dataList.value = response.data.rows ? response.data.rows : [];
        total.value = response.data.total;
        loading.value = false;
    });
    // getFuTask().then(response => {
    //     taskList.value = response.data;
    // })
}

/** 获取省列表 */
function getProvinceData() {
    getProvince().then(response => {
        provinceData.value = response.data;
        provinceData.value.unshift({ id: '全国', name: '全国', value: '全国' })
    });
}

function getProvinceFormData() {
    getProvince().then(response => {
        provinceFormData.value = response.data;
        provinceFormData.value.unshift({ id: '全国', name: '全国', value: '全国' })
    });
}

const areaDisabled = ref(false)
const cityDisabled = ref(false)
function chooseProvince(value) {
    queryParams.value.city = null;
    queryParams.value.area = null;
    queryParams.value.cityId = null;
    queryParams.value.areaId = null;
    cityData.value = [];
    areaData.value = [];
    if (value == '全国') {
        cityDisabled.value = true
        areaDisabled.value = true
    } else {
        cityDisabled.value = false
        areaDisabled.value = false
        getChildArea(value).then(response => {
            cityData.value = response.data;
            cityData.value.unshift({ id: '全部', name: '全部', value: '全部' })
        });
    }
    queryParams.value.province = provinceData.value.find(item => item.id == value)?.name;
}

function chooseCity(value) {
    queryParams.value.area = null;
    queryParams.value.areaId = null;
    areaData.value = [];
    if (value == '全部') {
        areaDisabled.value = true
    } else {
        areaDisabled.value = false
        getChildArea(value).then(response => {
            areaData.value = response.data;
            areaData.value.unshift({ id: '全部', name: '全部', value: '全部' })
        });
    }
    queryParams.value.city = cityData.value.find(item => item.id == value)?.name
}

function chooseArea(value) {
    queryParams.value.area = areaData.value.find(item => item.id == value)?.name;
}

const areaFormDisabled = ref(false)
const cityFormDisabled = ref(false)
function chooseFormProvince(value) {
    form.value.cityId = null;
    form.value.areaId = null;
    form.value.city = null;
    form.value.area = null;
    cityFormData.value = [];
    areaFormData.value = [];
    if (value == '全国') {
        cityFormDisabled.value = true
        areaFormDisabled.value = true
    } else {
        cityFormDisabled.value = false
        areaFormDisabled.value = false
        getChildArea(value).then(response => {
            cityFormData.value = response.data;
            cityFormData.value.unshift({ id: '全部', name: '全部', value: '全部' })
        });
    }
    form.value.province = provinceData.value.find(item => item.id == value)?.name;
}

function chooseFormCity(value) {
    form.value.area = null;
    form.value.areaId = null;
    areaFormData.value = [];
    if (value == '全部') {
        areaFormDisabled.value = true
    } else {
        areaFormDisabled.value = false
        getChildArea(value).then(response => {
            areaFormData.value = response.data;
            areaFormData.value.unshift({ id: '全部', name: '全部', value: '全部' })
        });
    }
    form.value.city = cityFormData.value.find(item => item.id == value)?.name
}

function chooseFormArea(value) {
    form.value.area = areaFormData.value.find(item => item.id == value)?.name;
}

//下载图件
function uploadImg() {
    saveAs(reportForm.value.attachList[0].url, '图件')
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {};
    proxy.resetForm("uploadRef");
    form.value.attachList = [];
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    queryParams.value.startTime = uploadTime.value ? uploadTime.value[0] + ' 00:00:00' : "";
    queryParams.value.endTime = uploadTime.value ? uploadTime.value[1] + ' 23:59:59' : "";
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    uploadTime.value = [];
    cityData.value = [];
    areaData.value = [];
    queryParams.value.province = null;
    queryParams.value.city = null;
    queryParams.value.area = null;
    queryParams.value.startTime = null;
    queryParams.value.endTime = null;
    uploadTime.value = null;
    cityDisabled.value = false
    areaDisabled.value = false
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.dmId);
    idFiles.value = selection.map(item => item.attachmentId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    isView.value = false;
    open.value = true;
    title.value = "图件上传";
    getProvinceFormData();
}

/** 提交按钮 */
function submitForm() {
    const fileList = JSON.parse(JSON.stringify(proxy.$refs["imgUpload"].fileList));
    const attachIds = [];
    for (var i = 0; i < fileList.length; i++) {
        attachIds.push(fileList[i].attachId)
    }
    form.value.attachmentId = attachIds.join(",");
    proxy.$refs['uploadRef'].validate(valid => {
        if (valid) {
            save()
            function save() {
                saveMap(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete() {
    if (!ids.value.length) {
        return proxy.$modal.msgWarning("请选择要删除的数据");
    }
    proxy.$modal.confirm('是否确认删除选中的数据项？').then(function () {
        return deleteByIds({ dmIdList: ids.value });
    }).then(() => {
        getList();
        proxy.$refs['tableRef'].clearSelection();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

// 查看
function handleView(row) {
    isView.value = true;
    title.value = '查看';
    getById(row.dmId).then(response => {
        open.value = true;
        reset();
        form.value = response.data;
        getChartClassifyList2(form.value.mapLevel1Category);
    });
}

// 下载
function handleDowon() {
    if (!idFiles.value.length) {
        return proxy.$modal.msgWarning("请选择要下载的数据");
    }
    proxy.download("/map/download", { attachIdList: idFiles.value }, '图件.zip');
    proxy.$refs['tableRef'].clearSelection();
}
// 一级分类
function getChartClassifyList() {
    getDictByDictDirId().then(res => {
        chartClassifyOption.value = res.data
    })
}

// 二级分类
function getChartClassifyList2(value) {
    getDictItemsByDictId({ dictId: value }).then(res => {
        if (open.value) {
            chartClassifyOption2.value = res.data
        } else {
            chartClassifyOption1.value = res.data
        }
    })
}

getList();
getChartClassifyList();
getProvinceData();
</script>

<style lang="scss" scoped>
.mt15 {
    margin-top: 15px;
}

.disabled .el-upload--picture-card {
    display: none;
}
</style>
<style lang="scss">
.el-dialog .el-dialog__body {
    padding: 20px 20px 0;
}

.el-table.chartTable {
    td.el-table__cell {
        border-right: var(--el-table-border) !important;
        border-bottom: var(--el-table-border) !important;
    }

    .el-table__header-wrapper th {
        background-color: #fff !important;
    }
}

.chartForm {
    .borderItem {
        width: 50%;
        border: 1px solid #ebeef5;
        border-bottom: none;
        margin: 0;
        display: inline-block;

        &:nth-child(2n) {
            border-left: none;
        }

        &>.el-row {
            height: 100%;
        }

        .checkboxTd,
        .mapTypeTd,
        .templateTd {
            padding: 15px 10px;
            min-height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .mapTypeTdContent {
            justify-content: start;
        }

        .checkboxTd,
        .mapTypeTd {
            border-right: 1px solid #ebeef5;
        }

        .templateTd {
            .el-form-item {
                margin: 0;
            }
        }
    }

    .borderItem:last-child,
    .borderItem:nth-last-child(2) {
        border-bottom: 1px solid #ebeef5;
    }
}
</style>
